package com.yinshu.teleshield.tkbase.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yinshu.teleshield.jwt.ContextUserDto;
import com.yinshu.teleshield.tkbase.base.entity.TKSuperEntity;
import com.yinshu.teleshield.tkbase.manager.SuperManager;
import com.yinshu.teleshield.tkbase.mybatis.conditions.Wraps;
import com.yinshu.teleshield.tkbase.request.PageParams;
import com.yinshu.teleshield.tkbase.service.SuperService;
import com.yinshu.teleshield.utils.ColumnUtil;
import com.yinshu.teleshield.utils.CommonBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

/**
 * 不含缓存的Service实现
 * <p>
 * 2，removeById：重写 ServiceImpl 类的方法，删除db
 * 3，removeByIds：重写 ServiceImpl 类的方法，删除db
 * 4，updateAllById： 新增的方法： 修改数据（所有字段）
 * 5，updateById：重写 ServiceImpl 类的方法，修改db后
 *
 * @param <M>      Manager
 * @param <Id>     ID
 * @param <Entity> 实体
 * @author yangjunxiong
 */
public abstract class SuperServiceImpl<M extends SuperManager<Entity>, Id extends Serializable, Entity extends TKSuperEntity<?>> implements SuperService<Id, Entity> {
    @Autowired
    protected M superManager;

    protected Class<M> managerClass = currentManagerClass();
    protected Class<Entity> entityClass = currentModelClass();
    protected Class<Id> idClass = currentIdClass();

    @Override
    public M getSuperManager() {
        return superManager;
    }

    @Override
    public Class<Entity> getEntityClass() {
        return entityClass;
    }

    @Override
    public Class<Id> getIdClass() {
        return idClass;
    }

    protected Class<M> currentManagerClass() {
        return (Class<M>) ReflectionKit.getSuperClassGenericType(this.getClass(), SuperServiceImpl.class, 0);
    }

    protected Class<Id> currentIdClass() {
        return (Class<Id>) ReflectionKit.getSuperClassGenericType(this.getClass(), SuperServiceImpl.class, 1);
    }

    protected Class<Entity> currentModelClass() {
        return (Class<Entity>) ReflectionKit.getSuperClassGenericType(this.getClass(), SuperServiceImpl.class, 2);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public <SaveVO> Entity save(SaveVO saveVO) {
        Entity entity = saveBefore(saveVO);
        this.getSuperManager().save(entity);
        saveAfter(saveVO, entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(List<Entity> entityList) {
        LocalDateTime now = LocalDateTime.now();
        String tenantId = (String) StpUtil.getExtra(ColumnUtil.getFieldName(ContextUserDto::getTenantId));
        String userId = (String) StpUtil.getExtra(ColumnUtil.getFieldName(ContextUserDto::getId));
        entityList.forEach(entity -> {
//            LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
//            if (Objects.nonNull(loginUser)) {
            entity.setTenantId(Long.valueOf(tenantId));
            entity.setCreator(Long.valueOf(userId));
            entity.setUpdater(Long.valueOf(userId));
//            }
            entity.setCreateTime(now);
            entity.setUpdateTime(now);
        });
        return this.getSuperManager().saveBatch(entityList);
    }

    /**
     * 保存之前处理参数等操作
     *
     * @param saveVO 保存VO
     */
    protected <SaveVO> Entity saveBefore(SaveVO saveVO) {
        Entity entity = BeanUtil.toBean(saveVO, getEntityClass());
        String tenantId = (String) StpUtil.getExtra(ColumnUtil.getFieldName(ContextUserDto::getTenantId));
        String userId = (String) StpUtil.getExtra(ColumnUtil.getFieldName(ContextUserDto::getId));
//        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
//        if (Objects.nonNull(loginUser)) {
        entity.setTenantId(Long.valueOf(tenantId));
        entity.setCreator(Long.valueOf(userId));
        entity.setUpdater(Long.valueOf(userId));
//        }
        LocalDateTime now = LocalDateTime.now();
        entity.setCreateTime(now);
        entity.setUpdateTime(now);
        return entity;
    }

    /**
     * 保存之后设置参数值，淘汰缓存等操作
     *
     * @param saveVO 保存VO
     * @param entity 实体
     */
    protected <SaveVO> void saveAfter(SaveVO saveVO, Entity entity) {
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public <UpdateVO> Entity updateById(UpdateVO updateVO) {
        Entity entity = updateBefore(updateVO);
        Entity byId = getSuperManager().getById((Long) entity.getId());
        CommonBeanUtils.copyProperties(entity, byId);
        getSuperManager().updateById(byId);
        updateAfter(updateVO, byId);
        return byId;
    }

    /**
     * 修改之前处理参数等操作
     *
     * @param updateVO 修改VO
     */
    protected <UpdateVO> Entity updateBefore(UpdateVO updateVO) {
        Entity entity = BeanUtil.toBean(updateVO, getEntityClass());
        String userId = (String) StpUtil.getExtra(ColumnUtil.getFieldName(ContextUserDto::getId));
//        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
//        if (Objects.nonNull(loginUser)) {
            entity.setUpdater(Long.valueOf(userId));
//        }
        entity.setUpdateTime(LocalDateTime.now());
        return entity;
    }

    /**
     * 修改之后设置参数值，淘汰缓存等操作
     *
     * @param updateVO 修改VO
     * @param entity   实体
     */
    protected <UpdateVO> void updateAfter(UpdateVO updateVO, Entity entity) {
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public <UpdateVO> Entity updateAllById(UpdateVO updateVO) {
        Entity entity = updateAllBefore(updateVO);
        Entity byId = getSuperManager().getById((Long) entity.getId());
        CommonBeanUtils.copyProperties(entity, byId);
        getSuperManager().updateAllById(byId);
        updateAllAfter(updateVO, byId);
        return byId;
    }

    /**
     * 修改之前处理参数等操作
     *
     * @param updateVO 修改VO
     */
    protected <UpdateVO> Entity updateAllBefore(UpdateVO updateVO) {
        Entity entity = BeanUtil.toBean(updateVO, getEntityClass());
        String userId = (String) StpUtil.getExtra(ColumnUtil.getFieldName(ContextUserDto::getId));
//        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
//        if (Objects.nonNull(loginUser)) {
            entity.setUpdater(Long.valueOf(userId));
//        }
        entity.setUpdateTime(LocalDateTime.now());
        return entity;
    }

    /**
     * 修改之后设置参数值，淘汰缓存等操作
     *
     * @param updateVO 修改VO
     * @param entity   实体
     */
    protected <UpdateVO> void updateAllAfter(UpdateVO updateVO, Entity entity) {
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Entity copy(Id id) {
        Entity old = getById(id);
        Assert.notNull(old, "您要复制的数据不存在或已被删除，请刷新重试");
        Entity entity = CommonBeanUtils.toBean(old, getEntityClass());
        entity.setId(null);
        superManager.save(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIds(Collection<Id> idList) {
        return getSuperManager().removeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean logicRemoveByIds(Collection<Id> idList) {
//        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        String userId = (String) StpUtil.getExtra(ColumnUtil.getFieldName(ContextUserDto::getId));
        for (Id id : idList) {
            Entity entity = getById(id);
            entity.setDeleted(1);
//            if (Objects.nonNull(loginUser)) {
                entity.setUpdater(Long.valueOf(userId));
//            }
            entity.setUpdateTime(LocalDateTime.now());
            getSuperManager().updateAllById(entity);
        }
        return true;
    }

    @Override
    @Transactional(readOnly = true)
    public Entity getById(Id id) {
        return getSuperManager().getById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Entity> list(MPJLambdaWrapper<Entity> queryWrapper) {
        return getSuperManager().list(queryWrapper);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Entity> listByIds(List<Id> ids) {
        return getSuperManager().listByIds(ids);
    }

    @Override
    @Transactional(readOnly = true)
    public <ResultVO, PageQuery> IPage<ResultVO> page(PageParams<PageQuery> params, Class<ResultVO> clazz) {
        // 构建分页参数(current、size)和排序字段等
        IPage<Entity> page = params.buildPage(getEntityClass());
        // 根据前端传递的参数，构建查询条件【提供给子类重写】【有默认实现】
        MPJLambdaWrapper<Entity> wrapper = Wraps.q(params.getExtra(), getEntityClass());
        handlerWrapper(wrapper, params);
        IPage<Entity> pageEntity = getSuperManager().page(page, wrapper);
        IPage<ResultVO> pageResultVO = CommonBeanUtils.toBeanPage(pageEntity, clazz);
        if (CollUtil.isEmpty(pageResultVO.getRecords())) {
            return pageResultVO;
        }
        handlerListResult(pageResultVO.getRecords());
        return pageResultVO;
    }

    @Override
    public <ResultVO> void handlerListResult(List<ResultVO> resultVO) {
    }

    @Override
    public <PageQuery> MPJLambdaWrapper<Entity> handlerWrapper(MPJLambdaWrapper<Entity> queryWrap, PageParams<PageQuery> params) {
        return queryWrap;
    }

}
